package com.example.springboot.security.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;
import com.example.springboot.security.LoginUser;
import com.example.springboot.security.util.SecurityUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.print.attribute.standard.Media;
import java.io.IOException;

/**
 * @author lei yu
 * @date 2024/05/20
 */
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private final static String TOKEN_HEADER = "Authorization";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        String actualToken = request.getHeader(TOKEN_HEADER);
        // 没有 actualToken，则直接跳过
        if (StrUtil.isNotEmpty(actualToken)) {
            String token = SecurityUtils.getToken();

            // 不通过
            if (!actualToken.equals(token)) {
                JakartaServletUtil.write(response, "访问令牌不存在", MediaType.APPLICATION_JSON_UTF8_VALUE);
                return;
            }
            // 通过后，将认证后的信息放入到 SecurityContext
            SecurityUtils.setLoginUser(new LoginUser(), request);
        }

        // 继续过滤链
        filterChain.doFilter(request, response);
    }
}
